<template>
	<view class="sticky_c">
		<uni-segmented-control :current="current" :values="classList" @clickItem="changeTab" :activeColor="primaryColor"
			styleType="text">
		</uni-segmented-control>
	</view>
	<view class="page">
		<list reqUrl="/api/uorderlist" :reqData="{ state: current+1 }" env ref="listInstance" formatData
			:handleFormat="handleFormat" emptyText="暂无订单" limit="5">
			<template v-slot="{ list }">
				<view class="order container" v-for="(item, orderIndex) in list" :key="item.order_id"
					@click="operation('look',orderIndex,item)">
					<view class="head_bar">
						<view class="left">
							<view>订单编号：{{ item.order_no }}</view>
							<view class="time">创建时间：{{ item.create_at }}</view>
						</view>
						<view class="right">
							<view class="status">
								{{item.pay_type_name}}
							</view>
							<view>{{ item.delivery_name }}</view>
						</view>
					</view>
					<view class="goods_c">
						<view v-for="(good,goodIndex) in item.goods" :key="goodIndex" class="good">
							<goods image_width="70px" image_height="70px" :image="imgHost + good.pic"
								:name="good.goods_title" :sub_name="good.goods_sub_title" :price_integer="good._integer"
								:price_decimal="good._decimal" :num="good.buy_num"></goods>
							<view v-if="current===0 && item.pay_type===3" class="payTip">线下支付成功，后台审核中，如有疑问请联系客服！</view>
						</view>
					</view>
					<view class="bottom_c">
						<view class="center">
							<text>合计：</text>
							<text class="special">￥{{ item.payment }}</text>
						</view>
						<view class="button_c">
							<view v-if="current!==0" @click.stop="operation('look', orderIndex,item)"
								hover-class="tapstate" class="button center">
								查看订单
							</view>
							<view v-if="current===0" @click.stop="operation('cancel', orderIndex,item)"
								hover-class="tapstate" class="button center">
								取消订单
							</view>
							<view v-if="current===0" @click.stop="operation('pay', orderIndex,item)"
								hover-class="tapstate" class="button center">继续支付</view>
							<view v-if="current===2" @click.stop="operation('receiving', orderIndex,item)"
								hover-class="tapstate" class="button center">
								确认收货
							</view>
						</view>
					</view>
				</view>
			</template>
		</list>
	</view>
	<!--取消订单原因弹出层-->
	<uni-popup ref="inputDialog" type="dialog">
		<uni-popup-dialog before-close mode="input" title="您确定取消该订单吗？" placeholder="请输入取消原因" @confirm="confirmCancel"
			@close="closeConfirmCancel">
		</uni-popup-dialog>
	</uni-popup>
	<!--支付方式选择弹出层-->
	<uni-popup ref="payMethosdPopupInstance" type="bottom" :safe-area="false">
		<view class="choose_pay_methods">
			<view class="closeable" hover-class="hover" @click="showPayPopup(false)">
				<uni-icons type="closeempty" size="20"></uni-icons>
			</view>
			<view class="title">请选择支付方式</view>
			<view v-if="enablePayWay.includes('1')" @click="onPayMethodSelect(2)" class="item" hover-class="tapstate">
				微信支付</view>
			<view v-if="enablePayWay.includes('2')" @click="onPayMethodSelect(3)" class="item" hover-class="tapstate">
				线下支付</view>
			<view v-if="enablePayWay.includes('5')" @click="onPayMethodSelect(5)" class="item" hover-class="tapstate">
				余额支付</view>
			<view class="brace"></view>
			<view class="cancel" @click="showPayPopup(false)" hover-class="tapstate">取消</view>
			<view class="env"></view>
		</view>
	</uni-popup>
</template>
<script setup>
	import { ref } from 'vue';
	import request from '@/utils/common/request/index';
	import { onPullDownRefresh, onReachBottom, onLoad, onShow } from '@dcloudio/uni-app';
	// #ifdef H5
	import { wechatyPay } from '@/utils/h5/index';
	// #endif
	import { useGetThemColor } from '@/hooks/useGetThemColor';
	import { sleep } from '@/utils/common/index';


	const { primaryColor, secondaryColor } = useGetThemColor();
	const { imgHost } = getApp().globalData;

	onLoad(option => {
		if (option.type !== undefined) current.value = Number(option.type);
	})

	// * 详情页微信支付成功，确认收货，取消订单成功，返回此页面时删除订单
	onShow(() => {
		const spliceIndex = uni.getStorageSync('spliceIndex');
		if (spliceIndex) {
			// let list = listInstance.value.captureList();
			// if (list.length > 0) {
			// 	list.splice(Number(spliceIndex), 1);
			// }
			listInstance.value.resetRequest();
			uni.removeStorage({
				key: 'spliceIndex'
			});
		}
	});

	// * tab
	let current = ref(0);
	let classList = ref(['待付款', '待发货', '待收货', '已完成']);
	const changeTab = ({ currentIndex }) => {
		current.value = currentIndex;
		listInstance.value.resetRequest();
	};

	// * 订单列表
	const listInstance = ref();
	// * 订单数据格式化函数
	const handleFormat = (res) => {
		let data = res.data;
		data.forEach(item => {
			item.goods.forEach(good => {
				[good._integer, good._decimal] = good.present_price.split('.');
			});
		});
		return data;
	};

	// * 按钮操作
	let operationActive = 0; //当前正在操作的索引
	let operationOrder = {}; //当前正在操作的订单数据
	const operation = (eventName, orderIndex, order) => {
		if (eventName === 'look') return onToDedail(orderIndex, order);
		if (eventName === 'cancel') return onCancel(orderIndex, order);
		if (eventName === 'receiving') return onReceiving(orderIndex, order);
		if (eventName === 'pay') return onPay(orderIndex, order);
	};
	const onToDedail = (index, order) => {
		uni.navigateTo({
			url: `/pages/order-detail/order-detail?id=${order.order_id}&index=${index}`
		});
	};

	// * 取消订单
	const inputDialog = ref();
	const onCancel = (index, order) => {
		operationActive = index;
		operationOrder = order;
		inputDialog.value.open();
	};
	const confirmCancel = reason => {
		if (!reason) return uni.showToast({
			title: '请输入取消原因',
			icon: "none"
		})
		request({
			method: 'POST',
			url: `/api/ucancelorder?order_id=${operationOrder.order_id}`,
			data: {
				cancel_remark: reason
			}
		}).then(() => {
			listInstance.value.resetRequest();
			uni.showToast({
				title: '取消成功',
				icon: 'success',
			});
			closeConfirmCancel();
		});
	};
	const closeConfirmCancel = () => { inputDialog.value.close() };


	// * 确认收货
	const onReceiving = (index, order) => {
		uni.showModal({
			title: '提示',
			content: '您确定已收到商品吗？',
			confirmColor: primaryColor.value,
			success(res) {
				if (res.cancel) return;
				request({
					url: `/api/uordercomplate?order_id=${order.order_id}`,
					method: 'POST'
				}).then(() => {
					listInstance.value.resetRequest();
					uni.showToast({
						title: '收货成功',
						icon: 'success',
					});
				})
			}
		});
	};


	// * 立即支付
	const enablePayWay = ref([]);
	request({
		url: '/api/reqpaytype'
	}).then(res => {
		enablePayWay.value = res;
	})
	const onPay = (index, order) => {
		operationActive = index;
		operationOrder = order;
		showPayPopup(true);
	};
	const payMethosdPopupInstance = ref(null);
	const onPayMethodSelect = (type) => {
		showPayPopup(false);
		request({
			url: '/api/dfkpay',
			method: 'POST',
			loadingTip: '处理中',
			data: {
				order_id: operationOrder.order_id,
				pay_type: type
			}
		}).then(async res => {
			if (type === 3) { //余额支付
				uni.showToast({
					title: '提交成功，审核中',
					duration: 2000,
				});
			} else if (type === 5) { //余额支付
				uni.showToast({
					title: '支付成功',
					mask: true,
					duration: 1000,
				});
				await sleep(800);
				listInstance.value.resetRequest();
			} else if (type === 2) { //微信支付
				wxPay(res);
			}
		})
	}

	const showPayPopup = (flag) => {
		flag ? payMethosdPopupInstance.value.open() : payMethosdPopupInstance.value.close();
	};
	const wxPay = (data) => {
		// #ifdef H5
		wechatyPay(data, async res => {
			if (res.err_msg == 'get_brand_wcpay_request:ok') {
				uni.showToast({
					title: '支付成功',
					mask: true
				});
				listInstance.value.resetRequest();
			}
			if (res.err_msg == 'get_brand_wcpay_request:cancel') {}
			if (res.err_msg == 'get_brand_wcpay_request:fail') {
				uni.showToast({
					title: '支付失败'
				});
			}
		});
		// #endif
	}

	/**下拉刷新事件 */
	onPullDownRefresh(() => {
		Promise.all([listInstance.value.resetRequest()]).finally(() => {
			uni.stopPullDownRefresh();
		});
	});
	// * 页面触底事件，不能删除，否则不能触发list组件触底事件
	onReachBottom(() => {});
</script>
<style lang="scss" scoped>
	.sticky_c {
		position: sticky;
		top: 0;
		z-index: 9;
		background-color: #fff;

		::v-deep .segmented-control {
			height: 42px !important;
		}

		::v-deep .segmented-control__item--text {
			padding: 8px 0 !important;
		}
	}

	.order {
		margin-bottom: 10px;
		border-radius: 10px;
		background-color: #fff;

		&:last-child {
			margin-bottom: 0;
		}

		.head_bar {
			display: flex;
			padding: 10px 0;
			color: #999;

			.left {
				flex: 1;
				padding-right: 10px;

				.time {
					margin-top: 2px;
				}
			}

			.right {
				flex-shrink: 0;
				text-align: right;

				.status {
					margin-bottom: 2px;
					color: v-bind(secondaryColor);
				}
			}
		}

		.goods_c {
			padding-bottom: 10px;
			border-top: 1px solid #f6f6f6;
			border-bottom: 1px solid #f6f6f6;

			.good {
				margin-top: 10px;
			}
		}

		.payTip {
			padding-top: 20px;
			text-align: right;
			font-size: 12px;
			color: v-bind(secondaryColor);
		}

		.bottom_c {
			display: flex;
			justify-content: space-between;
			padding: 16px 0;
			font-weight: bold;

			.special {
				color: v-bind(secondaryColor);
			}

			.button_c {
				display: flex;

				.button {
					width: 70px;
					height: 30px;
					border-radius: 20px;
					font-size: 13px;
				}

				.button:first-child {
					background-color: #f7f7f7;
					color: #999;
				}

				.button:last-child {
					margin-left: 10px;
					background-color: v-bind(primaryColor);
					color: #fff;
				}
			}

			.first {
				margin-right: 10px;
			}
		}
	}

	::v-deep .uni-button-color {
		color: v-bind(primaryColor);
	}

	.choose_pay_methods {
		position: relative;
		border-radius: 20px 20px 0 0;
		background-color: #fff;
		text-align: center;

		.closeable {
			position: absolute;
			right: 14px;
			top: 10px;
		}

		.title {
			padding-top: 12px;
			padding-bottom: 20px;
			font-size: 16px;
			font-weight: bold;
		}

		.item {
			padding: 18px 0;
			border-bottom: 1px solid #f5f5f5;
		}

		.brace {
			height: 8px;
			background-color: #f5f5f5;
		}

		.cancel {
			padding: 20px 0;
			color: #666;
		}
	}
</style>
<style>
	page {
		background-color: #f5f5f5;
	}
</style>